import configparser
import time
import os
import yaml
from selenium.webdriver.support.wait import WebDriverWait
from common.constants import YAML_PATH,ERROR_PATH


# 页面中常用的公共方法
class BasePage():
#     初始化页面
    def __init__(self, driver):
        self.driver = driver
#             读取yaml文件
        with open(YAML_PATH, 'r', encoding='utf-8') as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            print('Keys in YAML',data.keys())  # 打印yaml文件中的key值
            eles = data[self.__class__.__name__]
            print(f'eles的值{eles}')
            if eles is None:
                raise KeyError(f"'{self.__class__.__name__}' not found in YAML file")
            for ele in eles:  # 根据字典动态赋值
                self.__setattr__(ele, eles[ele])
    # 点击操作
    def click(self, *loc):
        self.driver.find_element(*loc).click()

        # 当元素存在就点击
    def click_ele_exist(self, *loc):
        self.driver.find_element(*loc)
        btns = self.driver.find_elements(*loc)
        # 如果出现用户协议弹出按钮
        if btns:
            btns[0].click()

    # 时间截图
    def save(self, filename):
        t = time.strftime("%Y%m%d%H%M", time.localtime())
        self.driver.save_screenshot(os.path.join(ERROR_PATH, t + filename))

    def find_element(self, loc):  # 元素定位
        try:
            WebDriverWait(self.driver, 30, 0.5).until(lambda driver: driver.find_element(loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            print(e)
            self.save('error.png')

        # 输入元素定位
    def input_text(self, text, *loc):
        self.driver.find_element(*loc).send_keys(text)

        # 根据css定位的元素
    def by_js(self, css):
        self.driver.execute_script(f"document.querySelector('{css}')")

        # 切换目标窗口
    def switch_window(self, target_title):
        # 切换到产品详情页窗口
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            # 判断切换到窗口句柄——-判断当前窗口的标题是否是：<header>中的<title>
            if target_title == self.driver.title:
                print("切换窗口句柄到产品详情页")
                return True

        # 获取目标元素文本
    def get_text(self, *locator):
        return self.driver.find_element(*locator).text

        # 需要读取数据config
    def get_url(self, section, key):
        # 获取ini文件中的url
        # section: 对应配置文件中的section
        # key: 对应配置文件中的key
        # 返回url
        # 读取配置文件
        config = configparser.ConfigParser()
        config.read('./data/config.ini', encoding='utf-8')
        # 获取url
        url = config.get(section, key)
        self.driver.get(url)
        # config = config_url(section, key)
        # print(f'url: {config}')
        # self.driver.get(config)
    # 后退
    def back(self):
        self.driver.back()

    # 前进
    def forward(self):
        self.driver.forword()

    # 退出
    def quit(self):
        self.driver.quit()
